package me.obstsalatt.guildera2.global;

import me.obstsalatt.guildera2.container.GWorld;
import me.obstsalatt.guildera2.core.Guild;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.util.ArrayList;

public class Main extends JavaPlugin {
    private EventDistributor eventDistributor;
    private PlayerManager playerManager;
    private ArrayList<GWorld> worlds;
    private ArrayList<Guild> guilds;



    public void onEnable() {
        getLogger().info("Lade GuildEra2!");

        playerManager = new PlayerManager(this);
        loadWorlds();
        loadGuilds();
        eventDistributor = new EventDistributor(this);
    }

    public void onDisable() {
        getLogger().info("Beende GuildEra2!");

        playerManager.savePlayers();
        saveWorlds();
        saveGuilds();
    }

    private void saveGuilds() {
        for(Guild g : guilds) {
            g.save();
        }
    }

    private void loadGuilds() {
        guilds = new ArrayList<Guild>();
        File dir = new File(getDataFolder().getAbsolutePath() + File.pathSeparator + "guildera2"
                                                              + File.pathSeparator + "guilds");
        for(File folder : dir.listFiles()) {
            if(folder.isDirectory()) {
                guilds.add(new Guild(this, folder.getName()));
            }
        }
    }

    private void saveWorlds() {
        for(GWorld w : worlds) {
            w.saveWorld();
        }
    }

    private void loadWorlds() {
        worlds = new ArrayList<GWorld>();
        for(World world : this.getServer().getWorlds()) {
            worlds.add(new GWorld(this, world));
        }
    }

    public ArrayList<GWorld> getWorldList() {
        return worlds;
    }

    public ArrayList<Guild> getGuildList() {
        return guilds;
    }

    public PlayerManager getPlayerManager() {
        return playerManager;
    }

    public GWorld findWorldByName(String name) {
        for(GWorld w : worlds) {
            if(w.getWorld().getName().equals(name)) {
                return w;
            }
        }
        return null;
    }

    public Guild findGuildByName(String name) {
        for(Guild g : guilds) {
            if(g.getName().equals(name)) {
                return g;
            }
        }
        return null;
    }
}
